"""
 -*- coding: utf-8-*-
 @File: configtest.py
 @Author: chen
 @time: 2023/09/17/ 15:47
"""
import pytest
import yaml

from test_cases import BASE_PATH
from tools.record_log import logger


@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    out = yield  # 获取钩子函数调用的结果
    report = out.get_result()
    failed_case_info = []  # 从钩子方法的调用结果中获取测试报告
    error_type = None  # 错误类型
    error_msg = None  # 错误信息
    error_longrepr = None  # 错误详情

    if report.outcome != "passed":
        # 如果运行时有相应的错误日志则捕获日志，并赋值到一个变量中
        if call.excinfo:
            error_type = call.excinfo.typename
            error_msg = call.excinfo.value.msg
            error_longrepr = str(out._result.longrepr)

        case_info = {
            "nodeid": report.nodeid,
            "result": report.outcome,
            "type": error_type,
            "msg": error_msg,
            "longrepr": error_longrepr
        }
        failed_case_info.append(case_info)
        # 将异常信息写入文件
        with open(BASE_PATH + './failed_record/fail_cases_info.yaml', 'a', encoding='utf-8') as f:
            yaml.dump(failed_case_info, f)

        logger.error(f'错误类型 =>> {error_type}，\n'
                     f'错误信息 =>> {error_msg}，\n'
                     f'错误详情 =>> {error_longrepr} \n')
